package com.pig4cloud.pig.module.controller.gate;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.gate.BarrierGate;
import com.pig4cloud.pig.module.api.entity.platform.PlatformPay;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.gate.IBarrierGateService;
import com.pig4cloud.pig.module.service.platform.IPlatformPayService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 道闸设备Controller
 *
 * @author ruoyi
 * @date 2023-06-12
 */
@Validated
@Api(value = "道闸设备控制器", tags = {"道闸设备管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/barrier/gate")
public class BarrierGateController {

    private final IBarrierGateService barrierGateService;
    private final IPropertyService propertyService;
    private final IEstateService estateService;
    private final IPlatformPayService platformPayService;
    @Value("${ruoyi.profile}")
    private String uploadPath;


    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

    /**
     * 查询道闸设备列表
     */
    @ApiOperation("查询道闸设备列表")
    @PreAuthorize("@pms.hasPermission('module:barrierGate:list')")
    @GetMapping("/list")
    public TableDataInfo<BarrierGate> list(@Validated BarrierGate barrierGate) {
        QueryWrapper<BarrierGate> qw = new QueryWrapper<>();
        if (barrierGate.getEstateId()!=null){
            qw.eq("estate_id",barrierGate.getEstateId());
        }
        if (barrierGate.getEstateName()!=null){
            qw.like("estate_Name",barrierGate.getEstateName());
        }
        if (barrierGate.getPropertyId()!=null){
            qw.eq("property_id",barrierGate.getPropertyId());
        }
        TableDataInfo<BarrierGate> td = PageUtils.buildDataInfo(barrierGateService.page(PageUtils.buildPage(),qw));
        List<BarrierGate> list = td.getData();
        for (BarrierGate list1:list){

            if(StrUtil.isNotEmpty(list1.getQrCode())){
                list1.setQrCode( imgUrl + list1.getQrCode() );
            }
            if (list1.getPayPlatformId()!=null){
                PlatformPay platformPay = platformPayService.getById(list1.getPayPlatformId());
                if (ObjectUtil.isNotEmpty(platformPay)){
                    list1.setPayPlatformName(platformPay.getPlatformName());
                }
            }
        }
        return td;
    }

    /**
     * 获取道闸设备详细信息
     */
    @ApiOperation("获取道闸设备详细信息")
    @PreAuthorize("@pms.hasPermission('module:barrierGate:query')")
    @GetMapping("/{id}")
    public R<BarrierGate> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        BarrierGate barrierGate = barrierGateService.getById(id);
        return R.ok(barrierGate);
    }

    /**
     * 新增道闸设备
     */
    @ApiOperation("新增道闸设备")
    @PreAuthorize("@pms.hasPermission('module:barrierGate:add')")
    @SysLog("道闸设备")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody BarrierGate barrierGate) {
        BarrierGate gate = barrierGateService.selectByUniqueColumn("gate_name",barrierGate.getGateName());
        if (gate!=null){
            return R.okByRow(0);
        }
        if (barrierGate.getPropertyId()!=null){
            Property property = propertyService.getById(barrierGate.getPropertyId());
            if (ObjectUtil.isNotEmpty(property)){
                barrierGate.setPropertyName(property.getPropertyName());
            }
        }
        if (barrierGate.getEstateId()!=null){
            Estate estate = estateService.getById(barrierGate.getEstateId());
            if (ObjectUtil.isNotEmpty(estate)){
                barrierGate.setEstateName(estate.getEstateName());
            }
        }
        boolean bl = barrierGateService.save(barrierGate);
        if(bl){
            try{
                BarrierGate gate1 = barrierGateService.selectByUniqueColumn("gate_name",barrierGate.getGateName());
                String qrCode = "";
                String fileName = "gate_" + gate1.getId() + ".jpg";
                String content = "https://www.sdyuedou.com/wxmini/gate/info?gate_id=" + barrierGate.getId();

                int upload_type = 0;//FileUploadUtils.TYPE_GATE;
                System.out.println("content:  "+ content);
                String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, barrierGate.getGateName(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                qrCode = img_key;
                barrierGate.setQrCode(qrCode);
                bl =  barrierGateService.updateById(barrierGate);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return R.okByRow(bl ? 1 : 0);
//        return R.okByRow(barrierGateService.save(barrierGate) ? 1 : 0);
    }

    /**
     * 修改道闸设备
     */
    @ApiOperation("修改道闸设备")
    @PreAuthorize("@pms.hasPermission('module:barrierGate:edit')")
    @SysLog("道闸设备")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody BarrierGate barrierGate) {
        if (barrierGate.getPropertyId()!=null){
            Property property = propertyService.getById(barrierGate.getPropertyId());
            if (ObjectUtil.isNotEmpty(property)){
                barrierGate.setPropertyName(property.getPropertyName());
            }
        }
        if (barrierGate.getEstateId()!=null){
            Estate estate = estateService.getById(barrierGate.getEstateId());
            if (ObjectUtil.isNotEmpty(estate)){
                barrierGate.setEstateName(estate.getEstateName());
            }
        }
        return R.okByRow(barrierGateService.updateById(barrierGate) ? 1 : 0);
    }

    /**
     * 删除道闸设备
     */
    @ApiOperation("删除道闸设备")
    @PreAuthorize("@pms.hasPermission('module:barrierGate:remove')")
    @SysLog("道闸设备")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(barrierGateService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    @SysLog("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('module:barrierGate:edit')")
    public R<Void> resetQrCode(@RequestBody BarrierGate gate) {
        if(gate.getId()!=null){
            try{
                gate = barrierGateService.getById(gate.getId());
                if(gate != null){
                    String fileName = "gate_" + gate.getId() + ".jpg";
                    String content = "https://www.sdyuedou.com/wxmini/gate/info?gate_id=" + gate.getId();
                    int upload_type = 0;//FileUploadUtils.TYPE_GATE;
                    System.out.println("content:  "+ content);
                    String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, gate.getGateName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
                    gate.setQrCode(img_key);
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (barrierGateService.updateById(gate)) {
                return R.ok();
            }
        }
        return R.failed();
    }
}
